指定 Hash 呈現區塊交易的訊息
訊息雖然很混亂看久大概就那幾個欄位
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
const publicClient = createPublicClient({
chain: mainnet,
transport: http(),
});
const transaction = await publicClient.getTransaction({
hash: '0xbc710a5f44f69da808bb1c6adf3e70fa9d8ed69d08282912de72bb34042c6a70',
});
console.log('transaction', transaction);
/*transaction {
type: 'eip1559',
blockHash: '0x16c60fa71bd501b8706bfc610926abd2f3f3ab518eb217098b78e0ce0f532ae2',
blockNumber: 18075787n,
from: '0xa6a688f107851131f0e1dce493ebbebfaf99203e',
gas: 242465n,
hash: '0xbc710a5f44f69da808bb1c6adf3e70fa9d8ed69d08282912de72bb34042c6a70',
input: '0x8d8798bfd69c275e3c033d90dccaba886790e04c96863d6651183f247690a2d4ffc474e0000000000000000000000000000000000000000000000000000000000000a4b10000000000000000000000000000000000000000000000000000000c2a99a8bb',
nonce: 84927,
to: '0x3666f603cc164936c1b87e207f36beba4ac5f18a',
transactionIndex: 578,
value: 0n,
v: 0n,
r: '0x321b72181bf9f048d239e4e921f1d6cdd7313a186af2901f4f08c95fbf87b83',
s: '0x46040761ba278c59c642eb476214fde749014448f2430593a4a571ce247659ce',
gasPrice: 10520166418n,
maxFeePerGas: 22573977776n,
maxPriorityFeePerGas: 90000000n,
chainId: 1,
accessList: [],
typeHex: '0x2'
}*/
getTransaction 獲得交易區塊結果
const transactionReceipt = await publicClient.getTransactionReceipt({
hash: '0xbc710a5f44f69da808bb1c6adf3e70fa9d8ed69d08282912de72bb34042c6a70',
});
getTransactionConfirmations 確定這個交易有多的 block 來完成
const confirmations = await publicClient.getTransactionConfirmations({
transactionReceipt,
});
這裡我們先下一個小節
對於區塊鏈的交易其實不是即時的,每個交易都是需要礦工打包的所以會有等待的時間,我們寫程式時,大概可以有這樣的想法 TxHash → TransactionReceipt → check OK → Transaction OK!
而有些交易就是特別大,不能立刻回應官方也很貼心的出了另外的 function
waitForTransactionReceip 等待確認交易完成
const waitTransaction = await publicClient.waitForTransactionReceipt({
confirmations: 5, // 確認幾次
hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
// timeout: 60_000, // time out 毫秒
// pollingInterval: 12_000 // 輪詢毫秒
// onReplaced: replacement => console.log(replacement) 如果你的設定都會的話,因該是不用這個,交易有狀況時才需要
});
這裡對 onReplaced 官方有說明
repriced
: Gas 費用被修改,與 maxFeePerGas
不同cancelled
: 交易已取消 ,如( Value ==== 0n)replaced
: 交易已被取代 (value
or data
不同)watchPendingTransactions 待處理的交易
這個我用比較少但是就是監控還沒完成的交易可以用這個
程式實作:
https://github.com/0xRory/ITHepleViem/blob/main/examples/3_7_1_Transaction.js
參考:
https://viem.sh/docs/actions/public/getTransaction.html
https://viem.sh/docs/actions/public/getTransactionConfirmations.html
https://viem.sh/docs/actions/public/getTransactionReceipt.html
https://viem.sh/docs/actions/public/waitForTransactionReceipt.html
https://viem.sh/docs/actions/public/watchPendingTransactions.html